package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.Result;
import com.itheima.pojo.Spec;
import com.itheima.service.SpecService;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 规格列表
 */
@RestController
@RequestMapping("/spec")
public class SpecController {
    @Reference
    private SpecService specService;

    //分页查询
    @RequestMapping("/findPage")
    public Result findPage(Integer page,Integer size,@RequestBody Map map){

        try {
            String name = (String) map.get("name");
            String options = (String) map.get("options");
            String id = (String) map.get("templateId");

            int templateId = Integer.parseInt(id);

            PageResult pageResult = specService.findPage(page, size, name, options, templateId);
            return new Result(true, MessageConstant.QUERY_SPEC_SUCCESS,pageResult);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_SPEC_FAIL);
        }
    }

    //新增
    @RequestMapping("/add")
    public Result add(@RequestBody Spec spec){
        try {
            specService.add(spec);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_SPEC_FAIL);
        }
        return new Result(true,MessageConstant.ADD_SPEC_SUCCESS);
    }

    //根据id查询数据
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Spec spec=specService.findById(id);
            return new Result(true,MessageConstant.QUERY_SPEC_SUCCESS,spec);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_SPEC_FAIL);
        }
    }

    //修改
    @RequestMapping("/update")
    public Result update(@RequestBody Spec spec){
        try {
            specService.update(spec);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.EDIT_SPEC_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_SPEC_SUCCESS);
    }

    //删除
    @RequestMapping("/delete")
    public Result delete(Integer id){
        try {
            specService.delete(id);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.DELETE_SPEC_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_SPEC_SUCCESS);
    }
}
